<?php
/**
 * Base.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/4/25
 * Time: 14:16
 */
namespace app\api\controller;

use think\Cache;

abstract class Base {
    protected $user = null;

    /**
     * Base constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $user_token = $_SERVER['HTTP_USER_TOKEN']??"";
        if($user_token === "")
        {
            $user_token = $_REQUEST['user_token']??"";
        }
        if($user_token === "")
        {
            throw new \Exception("TOKEN_ERROR_BY_PARAM",600);
        }
        // 切换到redis操作
        $cache = Cache::store('redis');
        $handler = $cache->handler();
        $userEncode = $handler->get($user_token);
        if( empty($userEncode) )
        {
            throw new \Exception("TOKEN_ERROR_EXPIRED",600);
        }
        $this->user = json_decode($userEncode,true);
        if(empty($this->user['id']))
        {
            // 需要重新登录
            throw new \Exception("TOKEN_ERROR_RE_LOGIN",600);
        }
        // 重新设置该用户过期时间
        if(!$handler->setex($user_token,60*60,$userEncode))
        {
            // 需要重新登录
            throw new \Exception("TOKEN_ERROR_RE_LOGIN",600);
        }
    }
}